import os
import shutil

from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand,CommandError
from django.urls import reverse
from django.test.client import Client


def get_pages():
	for name in os.listdir(settings.SITE_PAGE_DIRECTORY):
	    if name.endswith('.html'):
	        yield name[:-5]

class Command(BaseCommand):
	help = 'Build static site output';
	leave_locale_alone = True;
	def add_arguments(self,parser):
		parser.add_argument('args',nargs='*')

	def handle(self, *args,**options):
		settings.DEBUG=False;
		if args:
			pages = args;
			available = list(get_pages());
			invalid = []
			for page in pages:
				if page not in available:
					invalid.append(page);
			if invalid:
				msg = 'Invalid page:{}'.format(','.join(invalid));
				raise CommandError(msg)
		else:
			pages = get_pages()
			if os.path.exists(settings.SITE_OUTPUT_DIRECTORY):
				shutil.rmtree(settings.SITE_OUTPUT_DIRECTORY)
			os.mkdir(settings.SITE_OUTPUT_DIRECTORY)
		os.makedirs(settings.STATIC_ROOT, exist_ok=True)
		call_command('collectstatic',interactive=False,clear=True,verbosity=0)
		client = Client();
		for page in get_pages():
			url = reverse('page',kwargs={'sulg':page});
			response = client.get(url);
			if page == 'index':
				output_dir = settings.SITE_OUTPUT_DIRECTORY
			else:
				output_dir = os.path.join(settings.output_dir,page)
				os.makedirs(output_idr);
			with open(os.path.join(output_dir,'index.html'),'wb')as f:
				f.write(response.content)
